package leetcode.dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: https://leetcode.cn/problems/permutations-ii/
 * @Author Ammar
 * @Create 2023/7/19 21:33
 */
public class _47_全排列II {
    public List<List<Integer>> permuteUnique(int[] nums) {
        if (nums == null) return null;
        List<List<Integer>> list = new ArrayList<>();
        if (nums.length == 0) return list;
        dfs(0, nums, list);
        return list;
    }

    private void dfs(int idx, int[] nums, List<List<Integer>> list) {
        if (idx == nums.length) { // 最深层
            List<Integer> resultList = new ArrayList<>();
            for (int value : nums) {
                resultList.add(value);
            }
            list.add(resultList);
            return;
        }

        for (int i = idx; i < nums.length; i++) {
            // 不能直接下钻
            if (isRepeat(nums, idx, i)) continue;
            swap(nums, i, idx);
            dfs(idx + 1, nums, list);
            swap(nums, i, idx);
        }
    }

    private boolean isRepeat(int[] nums, int idx, int i) {
        for (int j = idx; j < i; j++) {
            if (nums[j] == nums[i]) return true;
        }
        return false;
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
